<?php

namespace app\index\controller;

use think\exception\ValidateException;
use app\model\Member;
use app\model\MemberCashlogs;
use app\model\Order;
use app\model\Paymethod;
use app\model\Viporder;
use app\model\Test;
use app\model\Config;

class PayController extends Base
{
    public function index()
    {
        $orderid = intval(input('post.orderid', '', 'serach_in'));
        $payment_code = input('post.payment_code', '', 'serach_in');
        $money = input('post.money', '', 'serach_in');
        $money = round($money, 2);
        $type = input('post.type', '', 'serach_in');
        $typearray = explode('-', $type);
        $type = $typearray[0];
        $typeparams = $typearray[1];

        if ($type == "order") {
            if (!empty($orderid)) {
                $orderdata =  Order::find($orderid);
                if (!empty($orderdata)) {
                    $orderdata = $orderdata->toArray();
                } else {
                    return $this->json(['errno' => 1, 'msg' => '订单不存在']);
                }

                //构造支付参数
                $paydata = array(
                    'body'          => '订单支付',
                    'out_trade_no'  => 'order-' . $orderdata['order_num_alias'],
                    'total_fee'     => $money,
                );
            }
        } elseif ($type == "vip") {
            $viporderdata =  Viporder::find($orderid);
            $paydata = array(
                'body'          => '购买会员等级',
                'out_trade_no'  => 'vip-' . $viporderdata['order_num_alias'],
                'total_fee'     => $money,
            );
        } elseif ($type == "additional") {
            if (!empty($orderid)) {
                $orderdata =  Order::find($orderid);
                if (!empty($orderdata)) {
                    $orderdata = $orderdata->toArray();
                } else {
                    return $this->json(['errno' => 1, 'msg' => '订单不存在']);
                }

                //构造支付参数
                $paydata = array(
                    'body'          => '支付尾款',
                    'out_trade_no'  => 'additional-' . $orderdata['order_num_alias'],
                    'total_fee'     => $money,
                );
            }
        } elseif ($type == "paybill") {

            $typeparams = str_replace('=', '_', $typeparams);
            $paydata = array(
                'body'          => '优惠买单',
                'out_trade_no'  => 'paybill-' . $typeparams,
                'total_fee'     => $money,
            );
            
        } elseif ($type == "recharge") {

            $paydata = array(
                'body'          => '充值',
                'out_trade_no'  => 'recharge-' . time(),
                'total_fee'     => $money,
            );
        } elseif ($type == "tongue") {

            $paydata = array(
                'body'          => 'AI舌诊',
                'out_trade_no'  => 'tongue-' . $orderid,
                'total_fee'     => $money,
            );
        }

        if ($payment_code == 'ali_pay') {
            //支付宝
            $pay_params = $this->alipay($paydata);
        } else {
//            $paydata['total_fee'] = 0.01;
            //微信支付生成支付参数，返回给小程序端
            if ($this->userInfo['ptype'] == 'app') {
                $pay_params = $this->wxapppay($paydata);
            } else {
                $pay_params = $this->wxpay($paydata);
            }
        }

        //$pay_params['url'] = gethost() . TP_APIURL .'/index.php/index/pay/notify/state/'.input('get.state');

        return $this->json($pay_params);
    }

    public function wxpay($paydata)
    {
        // 支付结果通知网址，如果不设置则会使用配置里的默认地址
        $paydata['notify_url'] = gethost() . TP_APIURL . '/index.php/index/pay/notify/state/' . input('get.state', '', 'serach_in') . '/from/' . input('get.from', '', 'serach_in');
        $paydata['trade_type'] = 'JSAPI';
        $paydata['openid'] = getFans()['openid'];
        $paydata['total_fee'] = floatval($paydata['total_fee'] * 100);

        try {
            $payment = \app\samos\wechat\WxPaymethod::makepay($this->userInfo['ptype']);

            $result = $payment->order->unify($paydata);

            if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
                Test::create(['title' => '微信支付失败信息', 'info' => serialize($result)]);
                $msg = '支付失败';
                return ['errno' => 1, 'msg' => $msg, 'message' => $msg, 'data' => $result];
            } else {
                $jssdk = $payment->jssdk;
                $payres = $jssdk->bridgeConfig($result['prepay_id'], false);
                return ['data' => $payres];
            }
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            return ['errno' => 1, 'msg' => $msg, 'message' => $msg, 'data' => $result];
        }
    }

    //微信支付回调
    public function notify()
    {
        //$xml = file_get_contents("php://input"); //回调回来的数据
        //Test::create(['title' => '微信支付回调', 'info' => serialize($xml)]);
        //file_put_contents('log/'.time() . "backdata.txt", $xml); //数据写入文件
        $response = \app\samos\wechat\WxPaymethod::makepay($this->userInfo['ptype'])->handlePaidNotify(function ($message, $fail) {
            //Test::create(['title' => '微信支付回调3', 'info' => $message['return_code']]);
            if ($message['return_code'] === 'SUCCESS')
            {
                // return_code 表示通信状态，不代表支付状态
                if ($message['result_code'] === 'SUCCESS')
                {
                    $message['total_fee'] = $message['total_fee'] / 100;
                    Paymethod::paysuccess($message);
                    return true;
                } elseif ($message['result_code'] === 'FAIL') {
                    // 用户支付失败
                    return true;
                }
            } else {
                return false;
            }
        });

        return $response;
    }

    public function wxapppay($paydata)
    {
        // 支付结果通知网址，如果不设置则会使用配置里的默认地址
        $paydata['notify_url'] = gethost() . TP_APIURL . '/index.php/index/pay/notify/state/' . input('get.state', '', 'serach_in') . '/from/' . input('get.from', '', 'serach_in');
        $paydata['total_fee'] = floatval($paydata['total_fee'] * 100);
        $result = [];
        try {
            $payment = \app\samos\wechat\WxPaymethod::makeAppOrderpayv3('app');
            $app_id = Config::getconfig('openweixin')['app_id'];
            $wxpay_settings = Paymethod::getwx_settings();

            $result = $payment->create('app', [
                'appid'        => $app_id,
                'mchid'        => trim($wxpay_settings['mchid']),
                'description'  => $paydata['body'],
                'out_trade_no' => $paydata['out_trade_no'],
                'notify_url'   => $paydata['notify_url'],
                'amount'       => ['total' => $paydata['total_fee'], 'currency' => 'CNY'],
//                'amount'       => ['total' => 0.01, 'currency' => 'CNY'],
            ]);

            $result['appid'] = $app_id;
            return ['data' => $result];
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            return ['errno' => 1, 'msg' => $msg, 'message' => $msg, 'data' => $result];
        }
    }

    //支付宝
    public function alipay($paydata)
    {

        try {
            $payment = \app\samos\ali\AliPaymethod::makepay($this->userInfo['ptype']);

            $result = $payment->apply([
                'out_trade_no' => $paydata['out_trade_no'], // 商户订单号
                'total_amount' => $paydata['total_fee'], // 支付金额
                'subject'      => $paydata['body'], // 支付订单描述
            ]);

            Test::create(['title' => '支付宝', 'info' => serialize($result)]);
            return ['data' => $result];
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            return ['errno' => 1, 'msg' => $msg, 'message' => $msg, 'data' => $result];
        }
    }
    //支付宝支付回调
    public function alinotify()
    {
        $xml = file_get_contents("php://input"); //回调回来的数据
        Test::create(['title' => '支付宝支付回调', 'info' => serialize($xml)]);

        $payment = \app\samos\ali\AliPaymethod::makepay($this->userInfo['ptype']);
        $message = $payment->notify();
        if (in_array($message['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
            //@todo 更新订单状态，支付完成
            $message['total_fee'] = $message['total_amount'];
            Paymethod::paysuccess($message);
            return true;
        } else {
            return false;
        }
    }
}
